package com.fjnldx.mes.service.scheduling.alarm.rule.inspector;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fjnldx.mes.domain.pojo.alarm.AlarmRules;
import com.fjnldx.mes.domain.pojo.alarm.enums.MonitoringTypeEnum;
import com.fjnldx.mes.service.scheduling.alarm.model.MonitorModel;
import com.fjnldx.mes.service.scheduling.alarm.rule.inspector.trigger.AlarmTrigger;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 辅机（固定表固定字段）
 */
@Service
public class AuxiliaryCheck implements AlarmRuleCheck {

    /**
     * 触发检查器
     */
    private final List<AlarmTrigger> alarmTriggerList;

    AuxiliaryCheck(List<AlarmTrigger> alarmTriggers) {
        alarmTriggerList = alarmTriggers;
    }

    /**
     * 监控类型
     */
    @Override
    public MonitoringTypeEnum monitoringType() {
        return MonitoringTypeEnum.AUXILIARY;
    }

    /**
     * 检查规则
     *
     * @param rule 规则
     */
    @Override
    public MonitorModel Check(AlarmRules rule) {
        JSONObject monitor = JSONObject.parseObject(rule.getMonitorValue());
        //工序
        String dicBh = monitor.getString("dicBh");

        //表名
        String table = monitor.getString("table");

        String devSn = monitor.getString("devSn");

        //监控属性
        String cs = monitor.getString("cs");

        //查询条件
        JSONArray condition = monitor.getJSONArray("condition") == null ? new JSONArray() : monitor.getJSONArray("condition");
        String conditionSql = condition.stream()
                .map(x -> {
                    JSONObject item = (JSONObject) x;
                    if (item.getString("key").equals("gongxu") && item.getString("value").equals("络筒")) {
                        item.remove("value");
                        item.put("value", "自络");
                    }
                    return item.getString("key")
                            + "="
                            + "'"
                            + item.getString("value")
                            + "'";
                })
                .collect(Collectors.joining(" and "));
        AlarmTrigger alarmTrigger = alarmTriggerList.stream().filter(trigger -> trigger.TriggerType() == rule.getTriggerType()).collect(Collectors.toList()).get(0);
        MonitorModel result = alarmTrigger.isTriggered(cs, table, devSn, rule.getTriggerValue(), conditionSql);
        if (result != null) {
            result.setDicBh(dicBh);
            result.setDevSn(devSn);
            result.setCs(cs);
            result.setCsName(monitor.getString("csName"));
        }
        return result;
    }
}
